
package com.grt192.spot.sensor.create;

import com.grt192.core.Sensor;
import com.grt192.spot.event.create.BumpEvent;
import com.grt192.spot.event.create.BumpListener;
import com.grt192.mechanism.iaroc.IRCreate;
import com.iaroc.irobot.IRobotCreate;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;

/**
 *
 * @author ajc
 */
public class GRTCreateBumpSensor extends Sensor {

    private IRobotCreate irc;
    private Vector bumpListeners;

    public GRTCreateBumpSensor(IRobotCreate irc) {
        this.irc = irc;
        bumpListeners = new Vector();
    }

    public void poll() {
        Hashtable prev = getState();
        setState("leftBump", irc.isBumpLeft());
        setState("rightBump", irc.isBumpRight());
        if(stateChanged(prev)){
            notifyBump();
        }
    }

    public void notifyBump() {
        for (int i = 0; i < bumpListeners.size(); i++) {
            ((BumpListener) bumpListeners.elementAt(i))
                    .bump(
                    new BumpEvent(this,
                    getState("leftBump") == TRUE ,
                    getState("rightBump")== TRUE));

        }
    }

    public void addBumpListener(BumpListener l) {
        bumpListeners.addElement(l);
    }

    public void removeBumpListener(BumpListener l) {
        bumpListeners.removeElement(l);
    }

    private boolean stateChanged(Hashtable prev) {
        Enumeration keys = prev.keys();
        while (keys.hasMoreElements()) {
            String key = (String) keys.nextElement();
            if (!prev.get(key).equals(getState().get(key))) {
                return true;
            }
        }
        return false;
    }
}
